package mil.af.amc.adpetracker.service;

import mil.af.amc.adpetracker.dao.DraDao;
import mil.af.amc.adpetracker.model.DRA;
import mil.af.amc.adpetracker.service.exceptions.DraAccountsStillAssignedException;
import mil.af.amc.adpetracker.service.exceptions.DraExistsException;
import mil.af.amc.adpetracker.service.exceptions.DraNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * Please Fill in this Javadoc
 *
 * @author TSgt Jason Ferguson
 */

@Service("draService")
public class DraServiceImpl implements DraService {

    private DraDao draDao;

    @Autowired
    public void setDraDao(DraDao draDao) {
        this.draDao = draDao;
    }

    public DRA addDra(Map draMap) throws DraExistsException {

        String draName = (String) draMap.get("draname");
        DRA dra = draDao.getDraByName(draName);
        if (dra != null) {
            throw new DraExistsException("DRA with name: " + draName + " already exists");
        }

        DRA newDra = new DRA();
        //dra.setId((Integer) draMap.get("draId"));
        newDra.setName((String) draMap.get("draName"));

        DRA result = draDao.save(newDra);
        return result;
//        int draId = draDao.add(newDra);
//        newDra.setId(draId);
//
//        return newDra;

    }

    public DRA editDra(Map draMap) throws DraNotFoundException {

        int draId = (Integer) draMap.get("draId");
        String draName = (String) draMap.get("draName");

        DRA dra = draDao.getById(draId);
        if (dra==null) {
            throw new DraNotFoundException("DRA#" + draId + " not found");
        }
        dra.setName(draName);

        draDao.save(dra);

        return dra;
    }

    public void deleteDra(Map draMap) throws DraNotFoundException, DraAccountsStillAssignedException {

        int draId = (Integer) draMap.get("draId");

        DRA dra = draDao.getById(draId);
        if (dra==null) {
            throw new DraNotFoundException("DRA#" + draId + " not found");
        }

        if (dra.getAdpeAccounts().size() > 0) {
            throw new DraAccountsStillAssignedException("DRA#" + draId + "still has assigned ADPE accounts");
        }

        draDao.delete(dra);
    }

    public DRA getById(int draId) throws DraNotFoundException {

        DRA dra = draDao.getById(draId);
        if (dra==null) {
            throw new DraNotFoundException("DRA#" + draId + " not found");
        }

        return dra;
    }

    public List<DRA> getAll() {

        return draDao.getAll();
    }
}
